/**
 * 说明： 是一个按钮类自定义控件的示例
 * */
var object;
var fieldMapList;
(function(factory){
    var nameSpace = 'field_1267193202406241001';
    if(!window[nameSpace]){
        var Builder = factory();
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
        window[nameSpace].isNotNull = function (obj) {
            return true;
        };
    }
})(function(){
    /**
     * 构造函数
     * @param options
     * @constructor
     */
    function App(options) {
        var self = this;
        //初始化参数
        self.initParams(options);
        //初始化dom
        self.initDom();
        //事件
        self.events();
    }

    App.prototype = {
        initParams : function (options) {
            object = options;
            var self = this;
            self.adaptation = options.adaptation;
            self.privateId = options.privateId;
            self.messageObj = options.getData;
            self.preUrl = options.url_prefix;
        },
        initDom : function () {
            var self = this;
            dynamicLoading.css(self.preUrl + 'css/secondDetailTableBtn.css');
            self.appendChildDom();
        },
        events : function () {
            var self = this;
            // 监听是否数据刷新
            self.adaptation.ObserverEvent.listen('Event' + self.privateId, function() {
                self.messageObj = self.adaptation.childrenGetData(self.privateId);
                self.appendChildDom();
            });
        },
        appendChildDom : function () {
            var self = this;
            var domStructure = '<section class="customButton_box_content">'+
                '<div class="customButton_class_box '+ self.privateId + '" title="' + self.messageObj.display.escapeHTML() + '">'+ self.messageObj.display.escapeHTML() +'</div>'+
                '</section>'
            // '<button id="importNewBtn" style="visibility: visible"'+attributes[0].name+' '+attributes[1].name+'   type="button" class="cap4-button-base cap4-toolbar-item cap4-button-bar cap4-button-bar-medium" >'+
            // '<i data-v-f44f15d6="" class="CAP  cap-icon-import" style="color: rgb(69, 190, 133);"></i>'+
            // '<span id="myspan" data-v-f44f15d6="" >' +self.options.__vue__._props.data.name+
            // '</span>'+
            // '</button>'



            // var domStructure = '<section class="customButton_box_content">'+
            //     '<div class="customButton_class_box '+ self.privateId + '" title="' + self.messageObj.display.escapeHTML() + '">'+ self.messageObj.display.escapeHTML() +'</div>'+
            //     '</section>';
            document.querySelector('#' + self.privateId).innerHTML = domStructure;

            var jumpFun = function() {
                debugger
                var subData = csdk.core.getFormData()
                var masterId = subData.metadata.content.contentDataId;
                var recordId = self.messageObj.recordId
                var privateId = self.privateId
                var tableName = object.formMessage.tableName
                localStorage.setItem("masterId",masterId);
                localStorage.setItem("recordId",recordId);

                dialog(self.preUrl + "/html/secondDetail.html","二级明细扩展",masterId,recordId,tableName)
                //获取表单名称

                //获取当前选中的行数据
                // var recordData = csdk.core.getSelectedRecord(tableName);
                // window.open(self.preUrl + "/html/secondDetail.html","单独窗口",'height=300,width=600,top=300,left=200,toolbar=no,menubar=no, scrollbars=no,resizable=no,location=no, status=no,titlebar=no');
                console.log("获取到的private："+privateId)
            };

            document.querySelector('.' + self.privateId).removeEventListener('click',jumpFun);
            document.querySelector('.' + self.privateId).addEventListener('click',jumpFun);
            //渲染隐藏权限
            if (self.messageObj.auth === 'hide') {
                document.querySelector('#' + self.privateId).innerHTML = '<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>';
            }
        },

        dealCdtMapping : function (opt) {
            $.ajax({
                url: '/seeyon/rest/cap4/formquerybtn/dealCdtMapping?formId=' + opt.formId + '&fieldName=' + opt.fieldName + '&formDataId=' + opt.formDataId + '&formSubDataId=' + opt.formSubDataId + '&designId=' + opt.designId,
                success: function (data) {
                    if(opt.callback && typeof opt.callback === 'function')
                        opt.callback.apply();
                },
                error: function (e) {
                    if(e.message){
                        top.$.error(e.message);
                    }else{
                        top.$.error('处理筛查条件出错...');
                    }
                }
            });
        }
    };


    var dialog = function (url,title,masterId,privateId,tableName){
        var dialog = $.dialog({
            url:url,
            width: document.documentElement.clientWidth || document.body.clientWidth,
            height: (document.documentElement.clientHeight || document.body.clientHeight) - 120,
            title: title,//调用模板
            targetWindow: getCtpTop(),
            buttons: [{
                text: "确定", //确定
                btnType:1,
                isEmphasize:true,
                handler: function () {
                    debugger
                    var idTest = localStorage.getItem("idTest")
                    idTest = JSON.parse(idTest)
                    var secondDetailData = {}
                    secondDetailData.masterId = masterId;
                    secondDetailData.recordId = privateId;
                    secondDetailData.sencondData = idTest;
                    saveData(secondDetailData)
                    //获取需要回写的字段数据
                    writeBackField()
                    //回写表单数据
                    writeBackFieldData(privateId,fieldMapList,idTest,tableName)

                    //删除缓存数据
                    localStorage.removeItem("idTest")
                    dialog.close();
                }
            }, {
                text: "取消", //取消
                handler: function () {
                    //删除缓存数据
                    localStorage.removeItem("idTest")
                    isFormSubmit = true;
                    dialog.close();
                }
            }]
        });
    }


    //获取需要回写的字段数据
    var writeBackField = function (){
        $.ajax({
            url: "/seeyon/rest/jssdk/getWriteBackField",
            type: "GET",
            processData: false,
            contentType: "application/json;charset=UTF-8",
            async:false,
            error: function (data) {

            },
            success: function (data) {
                console.log("获取到需要回写表单字段："+JSON.stringify(data))
                fieldMapList =  data;
            }
        });
    }

    //选择二级明细回写表单字段数据方法
    var writeBackFieldData = function (recordId,fieldMapList,idTest,tableName) {
        var data = [];
        for (var j = 0; j < fieldMapList.length; j++) {
            var fieldDataMap = {}
            var dataField = fieldMapList[j]["dataField"]
            var jsHxField = fieldMapList[j]["jsHxField"]
            var dataFieldValue = "";
            //获取字段数据
            for (var i = 0; i < idTest.length; i++) {
                var dataMap = idTest[i]
                dataFieldValue += dataMap[dataField]+"、";

            }
            dataFieldValue = dataFieldValue.substring(0,dataFieldValue.length-1);
            fieldDataMap.fieldId = jsHxField;
            fieldDataMap.tableName = tableName;
            fieldDataMap.recordId = recordId;
            fieldDataMap.fieldData = {
                value:dataFieldValue,
                display:dataFieldValue,
                auth:'browse'
            };
            data.push(fieldDataMap);
        }
        //开始回写字段信息
        csdk.core.setFieldData(data);
    }





    //保存数据
    var saveData = function (secondDetailData){
        console.log("准备保存的数据："+JSON.stringify(secondDetailData))
        $.ajax({
            url: "/seeyon/rest/jssdk/saveSencondDatail",
            data: JSON.stringify(secondDetailData),
            type: "POST",
            processData: false,
            contentType: "application/json;charset=UTF-8",
            async:false,
            error: function (data) {

            },
            success: function (data) {
                if(data.code === '200'){
                    csdk.util.alert("保存二级明细数据成功")
                }else{
                    csdk.util.alert("保存二级明细数据异常，请联系管理员！！！")
                }
            }
        });
    }


    var dynamicLoading = {
        css: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = path;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link);
        },
        js: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = path;
            script.type = 'text/javascript';
            head.appendChild(script);
        }
    }

    return App;
});
